var pictureRenders = function() {
	var IMAGE_PATH = "/PictureCentral/images/userImages/";
	var PICTURE_ICON_PATH = "/PictureCentral/images/picture/";
	
	return {
		imageActionRender : function(value, metadata, jsonObject, rowIndex, colIndex, store) {
			var image = "<span onclick='javascript:pictureForms.showPicture("+jsonObject.id+");'><img src='"+value+"' title='Info' onmouseover='this.style.cursor=\"pointer\";'></img></span>";
			return image;
		},

		downloadActionRender : function(value, metadata, jsonObject, rowIndex, colIndex, store) {
			var downloadAction = "<a href='"+shopCart.URL+"download?id="+jsonObject.id+"'><img src='"+PICTURE_ICON_PATH+"../shoppingcart/download.png' title='Download' onmouseover='this.style.cursor=\"pointer\";'></src></a>";
			return downloadAction;
		},
		
		editActionRender : function(value, metadata, jsonObject, rowIndex, colIndex, store) {
			var editAction = "<span onclick='javascript:pictureForms.editPicture("+jsonObject.id+");'><img src='"+PICTURE_ICON_PATH+"edit.gif' title='Edit' onmouseover='this.style.cursor=\"pointer\";'></src></span>";
			return editAction;
		},
		
		deleteActionRender : function(value, metadata, jsonObject, rowIndex, colIndex, store) {
			var delAction = "<span onclick='javascript:pictureHelper.removeRow("+jsonObject.id+");'><img src='"+PICTURE_ICON_PATH+"remove.gif' title='Delete' onmouseover='this.style.cursor=\"pointer\";'></src></span>";
			return delAction;
		}, 

		addToCartActionRender : function(value, metadata, jsonObject, rowIndex, colIndex, store) {
			var addToCartAction = "<span onclick='javascript:shoppingcartHelper.addToCart("+jsonObject.id+");'><img src='"+PICTURE_ICON_PATH+"../shoppingcart/shoppingcart_add.png' title='Add item to shopping cart' onmouseover='this.style.cursor=\"pointer\";'></src></span>";
			return addToCartAction;
		}, 

		imagePopulator : function(form, action) {
			var data = action.result.data;
			var imagePath = data.imagePath;
			var imageDiv = Ext.get("imagePath");
			imageDiv.createChild({tag:'img', src: imagePath});
		},
		
		thumbnailPopulator : function(form, action) {
			var data = action.result.data;
			var imagePath = data.thumbnailPath;
			var imageDiv = Ext.get("thumbnail");
			imageDiv.createChild({tag:'img', src: imagePath});
		}		
	};
}();

var pictureHelper = function() {
	var PICTURE_URL = "/PictureCentral/picture/";
	var tableId = null;
	function getPictureAttributes() {
        return [ 
          {name: 'id'},
          {name: 'thumbnailPath'},
          {name: 'imagePath'},
          {name: 'name'}, 
          {name: 'description'},
          {name: 'category'},
          {name: 'price'},
          {name: 'createdOn'} 
        ];
	}
	
	return {
	   getDataStore : function(action, jsonName, params, isFullActionURL) {
		   var url = '';
		   if(!params || params == null) {
			   params = [];
		   }
		   if(action && action != null) {
			   if(isFullActionURL) {
				   url = action;
			   } else {
				   url = PICTURE_URL+action;
			   }
		   }
		   
           // create the Data Store 
           var dataStore = new Ext.data.Store({ 
                 autoLoad: true, 
                 url: url,
              	 baseParams: params,
                 reader: new Ext.data.JsonReader({ 
                 results: 'total', 
                 title: 'title',
                 root:jsonName, 
                 id:'id' 
           }, 
           getPictureAttributes()
           )});
           return dataStore;
	   },
	   
	   getActionURL : function(action, id) {
		   var url = PICTURE_URL+action
		   if(id) {
			   url +='/'+id;
		   }
		   return url;
	   }, 
	   
	   setTableId : function(id) {
		   tableId = id;
	   },
	   
	   reload : function(tableId, row) {
		   pictureList();
	   },
	   
	   addRows : function(tableId, row) {
		   // TODO: currently refreshing the table should dynamically add a row
		   pictureHelper.reload();
	   },
	   
	   removeRow : function(pictureId) {
	        Ext.Ajax.request({
	    	   url: pictureHelper.getActionURL('delete'),
	    	   params: { pictureId: pictureId },
	    	   success: function() {/*Should just update the table}*/pictureHelper.reload();},
	    	   failure: function() {Ext.Msg.alert('Failure:','Unable to delete the picture!');}
	    	});
	   }
	   
  };
}();

var pictureForms = function() {
  // Constants
  var MAIN_WINDOW_DIV = 'picture-grid';
  var divId = 'picture-window';
  var formDivId = 'picture-form';
  
  // Attributes
  var formPanel = null;
  var formWindow = null;
  
    function getEditFields() {
    	return [
          pictureFields.getThumbnailImage(),
          pictureFields.getName(true),
          pictureFields.getDescription(true),
          pictureFields.getCategory(false),
          pictureFields.getPrice(true),
          pictureFields.getCreatedOn()
        ];
    };
    
    function getViewFields() {
    	return [
          pictureFields.getName(false),
          pictureFields.getDescription(false),
          pictureFields.getCategory(false),
          pictureFields.getPrice(false),
          pictureFields.getCreatedOn(),
          pictureFields.getImage(false)
        ];
    };
    
    function getCreateFields() {
    	return [
          pictureFields.getName(true),
          pictureFields.getDescription(true),
          pictureFields.getCategory(true, pictureHelper.getActionURL('categories')),
          pictureFields.getImage(true),
          pictureFields.getPrice(true)
        ];
    };
	
	function getFormPanel(title, width, formItems, actionUrl) {
		formPanel = new Ext.FormPanel({
            labelWidth: 75, // label settings here cascade unless overridden
            frame:true,
            title: title,
            bodyStyle:'padding:5px 5px 0',
            width: width,
            defaults: {width: 350},
            autoScroll: true,
            url: actionUrl,
            method: 'POST',
            fileUpload: true,
            timeout: 15000, //allow for big files on slow connections
            baseParams: { Command: 'UploadFileAttachments' }, // hidden values to pass along
            items: formItems
        });
	    return formPanel;
	};
	
	function getFormWindow(formPanel, width, height) {
		formWindow = new Ext.Window({
	        layout      : 'fit',
	        width       : width,
	        height      : height,
	        closable    : true,
	        plain       : true,
	        items       : formPanel,
	        modal       : true
	    });	
	    return formWindow;
	};
	
	function renderFormWindow() {
		var grid = Ext.get(MAIN_WINDOW_DIV);
		formWindow.show(grid);		
	};
	
	function init(picture_id) {
		formPanel = null;
		formWindow = null;
	}
	
  return {
  
    submit : function() {
	  formPanel.getForm().submit({
	    	 action:'submit',
	    	 waitMsg: 'Submitting form...',
	         success: pictureForms.submitSuccess,
	         failure: pictureForms.submitFailure
      });
    },
   
    submitSuccess : function(form, action) {
	   pictureHelper.addRows();
	   formWindow.close();
    },
    
    submitFailure : function(form, action) {
    	Ext.Msg.alert('Failure:','Unable to update the picture!');
    },
    
	showPicture : function(pictureId, tableId) {
	    init(); // always need to initialize the pictureForms
		var form = getFormPanel('Picture Info', 850, getViewFields() );
		var win = getFormWindow(form, 900, 500);
		win.addButton('Cancel', function(){ win.close();});
		formPanel.load({url:pictureHelper.getActionURL('show', pictureId), success:pictureRenders.imagePopulator})
        renderFormWindow();
	},
	createForm : function(tableId) {
		init(); // always need to initialize the pictureForms
	    var form = getFormPanel('Create Picture', 400, getCreateFields(), pictureHelper.getActionURL("save"));
		var win = getFormWindow(form, 500, 350);
		win.addButton('Save', pictureForms.submit);
		win.addButton('Cancel', function(){ win.close(); });
		renderFormWindow();
	},
	
	editPicture : function(pictureId, tableId) {
		init(); // always need to initialize the pictureForms
	    var form = getFormPanel('Edit Picture', 400, getEditFields(), pictureHelper.getActionURL("update", pictureId));
		var win = getFormWindow(form, 500, 350);
		win.addButton('Save', pictureForms.submit);
		win.addButton('Cancel', function(){ win.close(); });
		formPanel.load({url:pictureHelper.getActionURL('show', pictureId), success:pictureRenders.thumbnailPopulator})
		renderFormWindow();
	}
  };
}();

var pictureFields = function() {
	function createTextField(label, id, name, readOnly) {
        return new Ext.form.TextField({
       	  fieldLabel:label,                
       	  id:id,
       	  name:name,
       	  readOnly:readOnly
        });
	};
	
	function createTextArea(label, id, name, readOnly) {
	    return new Ext.form.TextArea({
	      fieldLabel:label,                
	      id:id,
	      name:name,
	      readOnly:readOnly
        });		
	};
	
	function createFileInput(label, id, name) {
        return new Ext.form.TextField({
      	  fieldLabel:label,                
      	  name:name,
      	  id:id,
          inputType: "file"
        });
	};	
	
	function createComboBox(label, id, name, url) {
		return new Ext.form.ComboBox({
            triggerAction: 'all',
            hiddenName: name,
            mode: 'local',
            lazyInit: true,
            displayField: 'displayValue',
            valueField: 'internalValue',
            forceSelection: true,
            typeAhead: true,
            inputType:'text',
            fieldLabel: label,
            store: new Ext.data.JsonStore({
                autoLoad: true,
                url: url,
                root: 'rows',
                fields:['internalValue', 'displayValue']
            })
		});	
	}
	
	return {
		getName : function(isEditable) {
		   var label = 'Name', name = 'name', id='name';
		   return createTextField(label, id, name, !isEditable);
	    },
	    
	    getDescription : function(isEditable) {
	    	var label = 'Description', name = 'description', id='description';
	    	return createTextArea(label, id, name, !isEditable);
	    },
	    
		getPrice : function(isEditable) {
	    	var label = 'Price', name = 'price', id='price';
	    	return createTextField(label, id, name, !isEditable);
		},	
		
		getCreatedOn : function() {
			var label = 'Created On', name = 'createdOn', id='createdOn';
			return createTextField(label, id, name, true);
		},
		
		getImage : function (isEditable) {
			var label = 'Image', name = 'file', id='file';
			if(isEditable) {
              return createFileInput(label, id, name);
			} else {
	          return new Ext.BoxComponent({
	          	  autoEl: {tag:'div', id:'imagePath'}
	          });
			}
		},
		
		getThumbnailImage : function () {
            return new Ext.BoxComponent({
	      	  autoEl: {tag:'div', id:'thumbnail'}
	        });
		},
		
		getCategory : function (isEditable, url) {
			var label = 'Category', name = 'category', id='category';
			if(isEditable) {
			  return createComboBox(label, id, name, url);
			} else {
			  return createTextField(label, id, name, true);
			}
		}
	};
}();

function pictureList(actionUrl, dataStore, columnModel) {
    var urlQuery = location.search;
	var href = '';
	if(actionUrl && actionUrl != null) {
		href = actionUrl
	} else {
		href = pictureHelper.getActionURL('list')+urlQuery;
	}
	var idx = urlQuery.indexOf('?');
	var params = [];
	if(idx >= 0) { 
	  var qry = urlQuery.substring(idx+1);
	  params = Ext.urlDecode(qry);
	}

	var pictureGrid = document.getElementById('picture-grid');
	pictureGrid.innerHTML ="";
	var tableId = 'pictureGridPanel';
	pictureHelper.setTableId(tableId);
    // create the Data Store
	var ds = [];
	if(dataStore && dataStore != null) {
		ds = dataStore;
	} else {
		ds = pictureHelper.getDataStore('extList','pictureList', params);
	}
	var tbar = [];
    var cm = [];
    if(columnModel && columnModel != null) {
    	cm = columnModel;
    } else {
    	// The logged in user can only modify or delete their own pictures and not other user's pictures
    	if(params.user) {
    		cm = new Ext.grid.ColumnModel({
    			columns: [ 
    			          {header: "", align:'center', width: 100, dataIndex: 'thumbnailPath', renderer:pictureRenders.imageActionRender}, 
    			          {header: "Name", width: 100, align:'left', dataIndex: 'name'}, 
    			          {header: "", width: 25, align:'center', dataIndex: 'id', renderer:pictureRenders.editActionRender},
    			          {header: "", width: 25, align:'center', dataIndex: 'id', renderer:pictureRenders.deleteActionRender},
    			          {header: "", width: 25, align:'center', dataIndex: 'id', renderer:pictureRenders.addToCartActionRender},
    			          {header: "Description",  width: 120, align:'left', dataIndex: 'description'}, 
    			          {header: "Category", width: 100, aling:'left', dataIndex: 'category'},
    			          {header: "Price", width: 50, align:'left', dataIndex: 'price'},
    			          {header: "Created On", width: 100, align:'left', dataIndex: 'createdOn'}
    			],
    			defaultSortable: true
    		});
    	} else {
    		cm = new Ext.grid.ColumnModel({
    			columns: [ 
    			          {header: "", align:'center', width: 100, dataIndex: 'thumbnailPath', renderer:pictureRenders.imageActionRender}, 
    			          {header: "Name", width: 100, align:'left', dataIndex: 'name'}, 
    			          {header: "", width: 25, align:'center', dataIndex: 'id', renderer:pictureRenders.addToCartActionRender},
    			          {header: "Description",  width: 120, align:'left', dataIndex: 'description'}, 
    			          {header: "Category", width: 100, aling:'left', dataIndex: 'category'},
    			          {header: "Price", width: 50, align:'left', dataIndex: 'price'},
    			          {header: "Created On", width: 100, align:'left', dataIndex: 'createdOn'}
    			],
    			defaultSortable: true
    		});
    	}
    	
    	tbar = [  
    	    new Ext.BoxComponent({
    	        autoEl: {
    	    		tag: 'img',
    	    		src: '/PictureCentral/images/picture/add.gif',
    	    		title: 'Add',
    	    		onmouseover: "this.style.cursor='pointer';",
    	    		onclick: 'pictureForms.createForm();' 	 
    	       	}
    	    })
    	];
    } 
    // create the grid 
    var grid = new Ext.grid.EditorGridPanel({ 
        ds: ds, 
        cm: cm,
        title: ' ',
        id: tableId,
   	    tbar: tbar,
        renderTo:'picture-grid', 
        stripeRows: true,
        autoHeight: true,
        autoWidth: true,
        //width:700, 
        height:480 
    });  	
    ds.on('load', function(store, records, options) { 
    	grid.setTitle(store.reader.jsonData.title);
    });
    return href;
}

function myLoadHandler(store, records, options) { 
	alert(store);
	var title = store.title;
}

var pictureCatgories = function() { 
	function createBRTag(items) {
		var br = new Ext.BoxComponent({
			autoEl: {
		        tag: 'br'
			}
		});
		items[items.length] = br;
	};

	function createActionTag(items, href, title) {
		var action = new Ext.BoxComponent({
			autoEl: {
		          tag: 'a',
		          html: title,
		          title: title,
		          href: href
			}
		});
		items[items.length] = action; 
	}
	
	return {
		loadCategoryActions : function() {
			
			Ext.Ajax.request({
				url : pictureHelper.getActionURL('categories'),
				method : 'GET',
				success : function(result, request) {
					var data = Ext.util.JSON.decode(result.responseText);
					pictureCatgories.displayCategoryActions(data);
				},
				failure : function(result, request) {
					Ext.MessageBox.alert('Failed', result.responseText);
				}
			});
			return pictureHelper.getActionURL('categoryActions');
		},

		displayCategoryActions : function(data) {
			
			var pictureGrid = document.getElementById('categoryActions');
			pictureGrid.innerHTML ="";

			var items = [];
			// All pictures list
			createActionTag(items, pictureHelper.getActionURL('list'), 'All');
			createBRTag(items);
			// User pictures list
			var userListHref = pictureHelper.getActionURL('list');
			userListHref+='?user=true';
			createActionTag(items, userListHref, 'My Pictures');
			createBRTag(items);
			createActionTag(items, shopCart.URL+'listOrders', 'My Orders');
			createBRTag(items);
			createActionTag(items, shopCart.URL+'orderedPictures', 'My Downloads');
			createBRTag(items);			
			
			var categories = data['rows'];
			
			for (var i=0,l=categories.length; i < l; i++) {
				var href = pictureHelper.getActionURL('list');
				href += '?category='+categories[i].internalValue;
				createActionTag(items, href, categories[i].displayValue);
				createBRTag(items);
			}
			
			var actionPanel = new Ext.Panel({
				border : false,
				renderTo : "categoryActions",
				items: items
			});
		}
	};
}();